package com.example.dreamlist2.goal;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dreamlist2.RegisterActivity;
import com.example.dreamlist2.StateInfo;

import com.example.dreamlist2.R;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class HabitAddActivity extends AppCompatActivity {

    ImageView img_ok, img_back;
    EditText text;
    String content;
    HabitItem habitItem;

    StateInfo stateInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.habit_add);

        img_ok = findViewById(R.id.habit_add_ok);
        img_back = findViewById(R.id.habit_add_back);
        text = findViewById(R.id.habit_textview);

        habitItem = new HabitItem();

        stateInfo = (StateInfo)getApplication();

        //取消并返回
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1);
                HabitAddActivity.this.finish();
            }
        });

        //确认并提交
        //habit:上传数据库
        img_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = text.getText().toString();
                submit_habit();
            }
        });


    }



    //上传信息至数据库
    private void submit_habit(){
        habitItem.setContent(content);
        habitItem.initTimes();
        habitItem.setUid(stateInfo.getUserin().getObjectId());
        //habitItem.setHid("null");
        //stateInfo.setHabitin(habitItem);

        habitItem.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    //habitItem.setHid(objectId);

                    Log.i("bmob","新建打卡事项成功");
                    Toast.makeText(HabitAddActivity.this, "添加成功！", Toast.LENGTH_SHORT);
                    setResult(1);
                    finish();
                }else{
                    Log.i("bmob","新建habit失败："+e.getMessage()+","+e.getErrorCode());
                    Toast.makeText(HabitAddActivity.this, "添加失败……", Toast.LENGTH_SHORT);
                }
            }
        });
    }
}